/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CONTROLLER_ADMIN;

import MODEL.DAO.TestResultsDao;
import MODEL.POJO.Testresults;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
/**
 *
 * @author samph
 */
@WebServlet(name = "SoanCauHoi", urlPatterns = {"/SoanCauHoi"})
public class SoanCauHoi extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out = response.getWriter();
        try {
           
            String action=request.getParameter("Action");
            ArrayList<CauHoi> arr = new ArrayList<CauHoi>();
            String path =this.getServletContext().getRealPath("/") + "questionBank.xml";
            arr = NganHangCauHoi.docDanhSachCauHoi(path);
            
             
            if(action != null && action.equals("insert")){
             
                String cauhoi = request.getParameter("cauhoi");
                String traloi1 =  request.getParameter("traloi1");
                String traloi2 =  request.getParameter("traloi2");
                String traloi3 =  request.getParameter("traloi3");
                String traloi4 =  request.getParameter("traloi4");
                int dokho = Integer.parseInt( request.getParameter("dokho"));
                CauHoi ch = new CauHoi();
                ch.setQuestion( cauhoi);
                ch.setAnswer_1(traloi1 );
                ch.setAnswer_2(traloi2);
                ch.setAnswer_3(traloi3);
                ch.setAnswer_4(traloi4);
                ch.setLevel(dokho);
                ch.setIdcauhoi(arr.get(arr.size()-1).getIdcauhoi()+1);                
                arr.add(ch);
                try {
                    int kq =GhiNhanCauHoi.ThemCauHoi(arr,path);
                    if(kq==1)
                    {
                        response.setContentType("text/javascript");
                        String s ="Đã insert thành công";
                        response.getOutputStream().print(s);
                        response.flushBuffer();
                        return;
                    }
                } catch (Exception e) {
                }
                
            }
            
            
            if(action != null && action.equals("insertfile")){
               
               
                    int iUpload = -1;
                    int soluong = 0;
                    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                    if (!isMultipart) {
                        
                    } else {
                        
                         
                   
                    
                    
                           FileItemFactory factory = new DiskFileItemFactory();
                           ServletFileUpload upload = new ServletFileUpload(factory);
                           List items = null;
                           try {
                                   items = upload.parseRequest(request);
                           } catch (FileUploadException e) {
                                   e.printStackTrace();
                           }
                           Iterator itr = items.iterator();
                           while (itr.hasNext()) {
                           FileItem item = (FileItem) itr.next();
                           if (item.isFormField()) {
                           } else {
                                   try {
                                           String itemName = item.getName();
                                           File savedFile = new File(this.getServletContext().getRealPath("/")+"Administrator/"+itemName);
                                           item.write(savedFile);  
                                           
                                           String s = savedFile.getAbsolutePath();
                                           ArrayList<CauHoi> arr_new = new ArrayList<CauHoi>();
                                           arr_new = NganHangCauHoi.docDanhSachCauHoi(s);
                                           int vitri  =arr.get(arr.size()-1).getIdcauhoi()+1;
                                          
                                           
                                           for(int k = 0; k < arr_new.size(); k++)
                                           {
                                               CauHoi ch = new CauHoi();
                                               ch = arr_new.get(k);
                                               ch.setIdcauhoi(vitri+k);
                                               arr.add(ch);
                                           }
                                           if(arr_new.size()>0)
                                           {   
                                                soluong = arr_new.size();
                                                int kq =GhiNhanCauHoi.ThemCauHoi(arr,path);
                                                if(kq==1)
                                                iUpload=1;
                                           }
                                           
                                           
                                            //out.println("<tr><td><b>Your file has been saved     at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath ("/")+"images"+"\\"+itemName+"</td></tr>");
                                   } catch (Exception e) {
                                           e.printStackTrace();
                                   }
                           }
                           }
                    }

                     try {
                        List<Testresults> dsTestresult = TestResultsDao.LayDanhSachKetQua();
                        request.setAttribute("dsTestresult",dsTestresult );
                         
                        request.setAttribute("insert", iUpload);
                        request.setAttribute("soluong", soluong);
                        request.getRequestDispatcher("Administrator/HomeAdmin.jsp").forward(request, response);
            
      } catch (Exception e) {
        e.printStackTrace();
      }
                    
               
            }
            
         }
         finally {            
           // out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
